/**
 *
 * @license
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 */

/**
 * @fileoverview This file contains the definition and code generator
 * for the custom text block used by the template generator.
 */

import * as Blockly from 'blockly/core';
import 'blockly/javascript';
import customInit from './customInit';

/**
 *
 * A custom text block has a next connection, and a name field.
 * The name field is the name of the Template object that the block
 * represents.
 */

Blockly.Blocks['textBlock'] = {
  init: function() {
    this.appendValueInput('next')
        .setCheck(null)
    // .appendField(new Blockly.FieldTextInput(""), "parent")
        .appendField(new Blockly.FieldTextInput('template object'), 'name');
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour(0);
    this.setTooltip('');
    this.setHelpUrl('');
    customInit(this);
  },
};

// The code generated by a custom block is a function of its name.

Blockly.JavaScript['textBlock'] = function(block) {
  console.log(block.getNextStatement());
  // Blockly.JavaScript.statementToCode(block,"next");
  const valueName = block.getFieldValue('name');

  // Information about template/template objects
  const templatesString = localStorage.getItem('templates');

  let code;

  if (templatesString) {
    // If information about the template/template object exists, we use it
    const templates = JSON.parse(templatesString);
    code = templates[valueName]['code'];
  }

  return [JSON.stringify(code), Blockly.JavaScript.ORDER_ATOMIC];
};
